package com.song.codesandbox.docker;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.PullResponseItem;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.LogContainerResultCallback;

import java.util.List;

public class DockerTest {

    public static void main(String[] args) throws InterruptedException {

        // 构建docker客户端
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();

        // 测试docker是否可用
        dockerClient.pingCmd().exec();

        // 拉取镜像
        String imageName = "nginx:latest";
        PullImageCmd pullImageCmd = dockerClient.pullImageCmd(imageName);
        PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
            @Override
            public void onNext(PullResponseItem item) {
                System.out.println("下载镜像:" + item.getStatus());
                super.onNext(item);
            }
        };
        pullImageCmd.exec(pullImageResultCallback).awaitCompletion();
        System.out.println((imageName + "下载完成"));

        // 创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(imageName);
        CreateContainerResponse containerResponse = containerCmd
                .withCmd("echo", "hello docker")
                .exec();
        String containerId = containerResponse.getId();
        System.out.println("创建容器: " + containerResponse);

        // 查看所有容器
        ListContainersCmd listContainersCmd = dockerClient.listContainersCmd().withShowAll(true);
        List<Container> containerList = listContainersCmd.exec();
        containerList.forEach(container -> {
            System.out.println("容器: " + container);
        });

        // 启动容器
        dockerClient.startContainerCmd(containerId).exec();

        // 查看日志
        LogContainerResultCallback logContainerResultCallback = new LogContainerResultCallback() {
            @Override
            public void onNext(Frame item) {
                System.out.println("日志: " + new String(item.getPayload()));
                super.onNext(item);
            }
        };
        dockerClient.logContainerCmd(containerId)
                .withStdErr(true)
                .withStdOut(true)
                .exec(logContainerResultCallback).awaitCompletion();

        // 删除容器
        dockerClient.removeContainerCmd(containerId).exec();

        // 删除镜像
        // dockerClient.removeImageCmd(containerId).withForce(true).exec();

    }
}